<template>
	<view class="order-modal">
		<!-- 头部区域：标题 + 取消 -->
		<view class="modal-header">
			<text class="modal-title">选择咨询订单</text>
			<text class="close-btn" @click="handleClose">取消选择</text>
		</view>

		<!-- 主标签：接单订单 / 我的发布 -->
		<view class="main-tabs">
			<view v-for="(tab, idx) in ['接单订单', '我的发布']" :key="idx" class="main-tab-item"
				:class="{ active: currentMainTab === idx }" @click="currentMainTab = idx">{{ tab }}</view>
		</view>

		<!-- 状态筛选标签（区分主标签） -->
		<view class="sub-tabs">
			<view v-for="(tab, idx) in getSubTabs()" :key="idx" class="sub-tab-item"
				:class="{ active: currentSubTab === idx }" @click="currentSubTab = idx">{{ tab }}</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y="true" @scrolltolower="loadMoreOrders" lower-threshold="50">
			<view v-for="(order, index) in filteredOrders" :key="index" class="order-item"
				:class="{ selected: selectedOrder === index }" @click="selectedOrder = index">


				<!-- 订单内容区 -->
				<view class="order-info">
					<view class="order-top">
						<view class="order-status-tag12"
							:style="{ background: getStatusStyle(order.status).bg, color: getStatusStyle(order.status).color }">
							{{ getStatusText(order.status) }}
						</view>

						<image class="status-img" :src="order.status_image" mode="widthFix"></image>
						<text class="order-title">{{ order.title }}</text>

					</view>
					<!-- 人员、时间、技能行 -->
					<view class="order-middle">
						<text class="people-time" v-if="order.people_num">{{ order.people_num }}</text>
						<text class="people-time" v-if="order.person_info">{{ order.person_info }}</text>
						<text class="people-time" v-if="order.time_range">{{ order.time_range }}</text>
						<text class="people-time" v-if="order.skill_des">{{ order.skill_desc }}</text>
					</view>
					<!-- 地址、距离行 -->
					<view class="order-bottom">
						<view class="order-bottom-vertical">
							<text class="address">地点：{{ order.address }}</text>
							<text class="distance">距您：{{ order.distance_info }}</text>
						</view>
						<image :src="getFullImageUrl('@/static/release/dh.png')" class="arrow"
							@click="gotoNavigation(order)"></image>
					</view>
					<hr style="height: 1rpx; background: #D0D4D7; margin: 30rpx -25rpx" />

					<!-- 酬金行 -->
					<view class="salary">
						<text>酬金： {{ order.salary }}</text>
						<!-- <image class="arrow" src="/static/image/logo.jpg" mode="widthFix"></image> -->
					</view>
				</view>
			</view>

			<!-- 加载更多提示 -->
			<view v-if="filteredOrders.length > 0" class="load-more-container">
				<view v-if="filteredOrders.length < total" class="loading-more">
					<view class="loading-spinner"></view>
					<text>正在加载更多...</text>
				</view>
				<view v-else-if="total > 0" class="no-more-data">
					<text>已经到底啦~</text>
				</view>
			</view>
		</scroll-view>

		<!-- 发送订单按钮 -->
		<view style="background: #FFFFFF; padding: 24rpx;">
			<button class="send-btn" :disabled="selectedOrder === -1" @click="handleSendOrder">发送订单</button>
		</view>

	</view>
</template>

<script>
import { request, getFullImageUrl, initBaseUrl } from '../../../../utils/request';
import { getLocation } from '../../../../utils/mapUtils';
import { ORDER_STATUS, JOB_STATUS, getOrderStatusText, getJobStatusText, getStatusStyle, getMyStatusStyle } from '../../../../utils/status';


export default {
	data() {
		return {
			currentMainTab: 0, // 0:接单订单 1:我的发布
			currentSubTab: 0,  // 状态筛选索引
			selectedOrder: -1, // 选中订单索引
			page: 1,           // 当前页码
			limit: 10,         // 每页条数
			total: 0,          // 总记录数
			isLoading: false,  // 添加加载状态变量
			// 订单数据
			orders: [
				// {
				// 	title: '会议充场兼职',
				// 	status: 1,
				// 	status_image: '/static/image/logo.jpg',
				// 	people_num: '2人',
				// 	person_info: '女生，20岁，165cm',
				// 	time_range: '05/24 09:30-18:00',
				// 	skill_desc: '会议跟拍、视频拍摄',
				// 	address: '海珠区新港东路某中心（交通便利）',
				// 	distance_info: '364m | 13分钟',
				// 	salary: '¥80元'
				// },
				// {
				// 	title: '搬家抬货',
				// 	status: 2,
				// 	status_image: '/static/image/logo.jpg',
				// 	people_num: '1人',
				// 	person_info: '女生，20岁，165cm',
				// 	time_range: '05/24 12:00-15:00',
				// 	skill_desc: '搬家抬货小帮手，正午一般货物积压见底，东西有望车东西午可拿',
				// 	address: '海珠区新港东路某中心（交通便利）',
				// 	distance_info: '364m | 13分钟',
				// 	salary: '¥99元'
				// },
				// {
				// 	title: '搬家抬货',
				// 	status: 1,
				// 	status_image: '/static/image/logo.jpg',
				// 	people_num: '1人',
				// 	person_info: '女生，20岁，165cm',
				// 	time_range: '05/24 12:00-15:00',
				// 	skill_desc: '搬家抬货小帮手，正午一般货物积压见底，东西有望车东西午可拿',
				// 	address: '海珠区新港东路某中心（交通便利）',
				// 	distance_info: '364m | 13分钟',
				// 	salary: '¥99元'
				// }
			]
		}
	},
	computed: {
		// 根据主标签+子标签筛选订单
		filteredOrders() {
			// 使用统一状态常量
			const statusMap = {
				0: { 0: null, 1: ORDER_STATUS.ACCEPTED, 2: ORDER_STATUS.IN_PROGRESS, 3: ORDER_STATUS.COMPLETED, 4: ORDER_STATUS.CANCELED },  // 接单订单状态映射(与订单中心保持一致)
				1: { 0: null, 1: JOB_STATUS.PENDING, 2: JOB_STATUS.ACCEPTED, 3: JOB_STATUS.IN_PROGRESS, 4: JOB_STATUS.COMPLETED, 5: JOB_STATUS.CANCELED }   // 我的发布状态映射
			};
			const status = statusMap[this.currentMainTab][this.currentSubTab];

			// 无状态筛选或无订单数据时直接返回
			if (status === null || !this.orders.length) {
				// 排除status为0的订单
				return this.orders.filter(order => order.status !== 0);
			}

			// 根据当前状态筛选订单，同时排除status为0的订单
			let result = this.orders.filter(order => order.status === status && order.status !== 0);

			return result;
		}
	},
	async created() {
		console.log('组件创建，开始获取数据');
		await initBaseUrl();
		await this.fetchOrders();
	},
	watch: {
		// 监听主标签变化
		currentMainTab: function () {
			this.currentSubTab = 0; // 重置子标签
			this.page = 1;
			this.fetchOrders(); // 主标签变化时请求数据
		},
		// 监听子标签变化
		currentSubTab: function () {
			this.page = 1;
			this.fetchOrders(); // 子标签变化时请求数据
		}
	},
	methods: {
		getFullImageUrl,
		// 新增：导航功能
		gotoNavigation(order) {
			// 调用uni-app的地图导航API
			uni.openLocation({
				latitude: parseFloat(order.latitude),
				longitude: parseFloat(order.longitude),
				name: '目的地',
				address: order.address,
				success: () => {
					console.log('导航已打开');
				},
				fail: (err) => {
					console.error('打开导航失败', err);
					uni.showToast({
						title: '无法打开导航',
						icon: 'none'
					});
				}
			});
		},

		// 新增：获取订单数据
		async fetchOrders() {
			this.isLoading = true;
			try {
				// 获取位置信息
				const location = await getLocation().catch(() => null);

				// 构建请求参数
				const url = this.currentMainTab === 0
					? '/Workerorders/order_list'
					: '/WorkerPosts/my_posts';

				// 状态映射表

				// 复用computed中的statusMap逻辑，确保状态映射一致
				const statusMap = {
					0: { 0: null, 1: ORDER_STATUS.ACCEPTED, 2: ORDER_STATUS.IN_PROGRESS, 3: ORDER_STATUS.COMPLETED, 4: ORDER_STATUS.CANCELED },  // 接单订单状态映射
					1: { 0: null, 1: JOB_STATUS.PENDING, 2: JOB_STATUS.ACCEPTED, 3: JOB_STATUS.IN_PROGRESS, 4: JOB_STATUS.COMPLETED, 5: JOB_STATUS.CANCELED }   // 我的发布状态映射
				};
				const status = statusMap[this.currentMainTab][this.currentSubTab];

				const params = {
					page: this.page,
					limit: this.limit,
					// 除开status为0的订单
					exclude_status: 0
				};

				// 添加状态筛选
				if (status !== null) {
					params.status = status;
				}

				// 添加位置信息
				if (location) {
					params.latitude = location.latitude;
					params.longitude = location.longitude;
				}

				// 发起请求
				const res = await request({
					url: url,
					method: 'GET',
					data: params
				});

				if (res.code === 200) {
					const newOrders = res.data || [];
					console.log("获取到的订单数据：", newOrders);
					if (this.page === 1) {
						this.orders = newOrders;
						this.selectedOrder = -1; // 重置选中状态
					} else {
						this.orders = [...this.orders, ...newOrders];
					}
					this.total = res.total || 0;
				}
			} catch (error) {
				console.error('获取订单数据失败:', error);
				uni.showToast({
					title: '获取订单失败',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},
		// 切换主标签时重置子标签
		getSubTabs() {
			// 仅返回标签数组，不执行数据请求
			return this.currentMainTab === 0
				? ['全部', '已接单', '进行中', '已结束', '已取消']
				: ['全部', '待接单', '已接单', '进行中', '已结束', '已取消']
		},

		// 关闭弹框（向父组件通知）
		handleClose() {
			this.$emit('close');
			// 小程序可能需要特殊处理
			if (typeof uni !== 'undefined') {
				uni.hideKeyboard();
			}
		},

		// 发送订单（向父组件传递选中订单）
		handleSendOrder() {
			if (this.selectedOrder === -1) return;
			const order = this.filteredOrders[this.selectedOrder];
			this.$emit('sendOrder', order); // 确保触发sendOrder事件并传递订单数据
			this.handleClose();
		},

		// 状态文案映射
		getStatusText(status) {
			// 根据当前主标签选择使用订单状态还是任务状态文本
			if (this.currentMainTab === 0) {
				return getOrderStatusText(status);
			} else {
				return getJobStatusText(status);
			}
		},

		// 状态背景色和字体颜色映射
		getStatusStyle(status) {
			// console.log("当前状态:",status);

			// 根据主标签类型调整状态值，确保样式正确
			if (this.currentMainTab === 1) { // 我的发布
				// JOB_STATUS 到 ORDER_STATUS 的映射
				return getMyStatusStyle(status);

			}

			// 使用统一状态样式获取函数
			return getStatusStyle(status);
		},

		// 加载更多订单
		async loadMoreOrders() {
			if (this.isLoading || this.filteredOrders.length >= this.total && this.total > 0) {
				return;
			}

			this.page++;
			await this.fetchOrders();
		},


	}
}
</script>

<style lang="scss">
// 订单选择弹框
.order-modal {
	position: relative;
	height: 90vh;
	background: #fff;
	border-radius: 35rpx;
	box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.1);
	z-index: 9999;
	box-sizing: border-box;
	padding: 0 32rpx;

	// 隐藏时 translateY 到底部
	&.hidden {
		transform: translateY(100%);
	}

	// 头部
	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 0;

		.modal-title {
			font-family: Source Han Sans CN;
			font-weight: bold;
			font-size: 32rpx;
			color: #0E1C37;
		}

		.close-btn {
			background: #EEF2F3;
			border-radius: 10rpx;
			padding: 10rpx;
			font-family: Source Han Sans CN;
			font-weight: 500;
			font-size: 22rpx;
			color: #888B9A;
		}
	}

	// 主标签
	.main-tabs {
		display: flex;
		margin: 24rpx 0 40rpx;
		margin-top: 10rpx;

		.main-tab-item {
			text-align: center;
			font-family: Source Han Sans CN;
			font-weight: 400;
			font-size: 32rpx;
			color: #888B9A;
			line-height: 26rpx;
			padding: 16rpx 0;
			position: relative;

			&:first-child {
				margin-right: 66rpx;
			}

			&.active {
				font-family: Source Han Sans CN;
				font-weight: 500;
				font-size: 36rpx;
				color: #0E1C37;
				line-height: 26rpx;
			}

			&.active::after {
				content: '';
				position: absolute;
				bottom: -15rpx;
				left: calc(50% - 34rpx);
				width: 68rpx;
				height: 7rpx;
				background: #BEFF32;
				border-radius: 0rpx 5rpx 5rpx 0rpx;
			}
		}
	}

	// 子标签（状态筛选）
	.sub-tabs {
		display: flex;
		margin: 25rpx 0 0;
		background-color: #EEF2F3;
		border-radius: 30rpx;
		overflow-x: auto;
		white-space: nowrap;
		scrollbar-width: none;

		/* 隐藏滚动条 */
		&::-webkit-scrollbar {
			display: none;
		}

		.sub-tab-item {
			font-family: Source Han Sans CN;
			font-weight: 400;
			font-size: 22rpx;
			color: #888B9A;
			line-height: 26rpx;
			padding: 18rpx 28rpx;
			margin: 0 5rpx;
			border-radius: 32rpx;
			transition: all 0.2s;

			&.active {
				background: #BEFF33;
				color: #0E1C37;
			}

			// 移除未选中状态的边框
			&:not(.active) {
				border: none;
			}
		}
	}

	// 订单列表
	.order-list {
		height: calc(90vh - 400rpx);
		margin: 24rpx 0 0;
		box-sizing: border-box;

		.order-item {
			padding: 24rpx;
			border: 2rpx solid #EDEDED;
			margin-bottom: 24rpx;
			transition: all 0.2s;
			background: #EEF2F3;
			border-radius: 26rpx;
			box-sizing: border-box;
			width: 100%;

			// 选中样式，适配效果图
			&.selected {
				border-color: #BEFF33;
				box-shadow: 0 0 16rpx rgba(76, 217, 100, 0.2);
			}



			// 订单内容
			.order-info {

				.order-top {
					display: flex;
					align-items: center;
					margin-bottom: 12rpx;
					flex-wrap: wrap;

					// 状态标签
					.order-status-tag12 {
						width: 82rpx;
						min-width: 50rpx;
						text-align: center;
						font-size: 22rpx;
						padding: 2rpx 6rpx;
						border-radius: 5rpx;
						margin-right: 16rpx;
						flex-shrink: 0;
					
				}

				.order-title {
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
					flex: 1;
					word-break: break-all;
					line-height: 1.4;
				}

				.status-img {
					width: 40rpx;
					height: 40rpx;
					margin-right: 14rpx;
					flex-shrink: 0;
				}
			}

			.order-middle {
				display: flex;
				flex-wrap: wrap;
				margin-bottom: 12rpx;
				max-width: 100%;

				.people-time {
					font-family: Source Han Sans CN;
					font-weight: 400;
					font-size: 22rpx;
					color: #888B9A;
					margin-right: 12rpx;
					background: #FFFFFF;
					border-radius: 10rpx;
					padding: 8rpx 12rpx;
					margin-bottom: 10rpx;
					word-break: break-all;
					max-width: 100%;
				}


			}

			.order-bottom {
				display: flex;
				align-items: flex-start;
				justify-content: space-between;
				font-size: 24rpx;
				color: #999;
				margin-bottom: 12rpx;

				.order-bottom-vertical {
					display: flex;
					flex-direction: column;
					flex: 1;
					min-width: 0;
				}

				.address {
					flex: 1;
					margin-bottom: 8rpx;
					word-break: break-all;
					line-height: 1.4;
				}

				.distance {
					margin-right: 12rpx;
					white-space: nowrap;
				}

				.arrow {
					width: 36rpx;
					height: 36rpx;
					flex-shrink: 0;
					margin-left: 10rpx;
				}
			}

			.salary {
				display: flex;
				align-items: center;
				font-family: Source Han Sans CN;
				font-weight: 500;
				font-size: 26rpx;
				color: #F71737;
				margin: 35rpx 0 18rpx;

				.arrow {
					width: 36rpx;
					height: 36rpx;
					margin-left: 18rpx;
				}
			}
		}
	}
}


// 发送按钮，适配效果图样式
.send-btn {
	position: absolute;
	bottom: 12rpx;
	left: calc((100% - 90%) / 2);
	display: block;
	width: 90%;
	height: 83rpx;
	margin: 32rpx auto 20rpx;
	background: #BEFF33;
	font-family: Source Han Sans CN;
	font-weight: 500;
	font-size: 32rpx;
	color: #0E1C37;
	padding: 3rpx 0;
	border-radius: 12rpx;
	letter-spacing: 2rpx;

	&:disabled {
		background: #D0D4D7;
		border-radius: 12rpx;
		font-family: Source Han Sans CN;
		font-weight: 500;
		font-size: 32rpx;
		color: #888B9A;
	}
}

wx-button[disabled]:not([type]),
wx-button[disabled][type=default] {
	background: #D0D4D7;
	border-radius: 12rpx;
	font-family: Source Han Sans CN;
	font-weight: 500;
	font-size: 32rpx;
	color: #888B9A;

}

// 加载更多样式
.load-more-container {
	padding: 20rpx 0;
	text-align: center;

	.loading-more {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #888B9A;

		.loading-spinner {
			width: 24rpx;
			height: 24rpx;
			border: 2rpx solid #888B9A;
			border-top: 2rpx solid transparent;
			border-radius: 50%;
			margin-right: 10rpx;
			animation: spin 1s linear infinite;
		}
	}

	.no-more-data {
		font-size: 24rpx;
		color: #888B9A;
		padding: 20rpx 0;
	}
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}
}
</style>
